<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <my-breadcrumb>发布文章</my-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="今天等我来" />
        </el-form-item>

        <el-form-item label="内容" prop="content" ref="formItem">
          <quill-editor
            v-model="form.content"
            :options="editorOption"
            class="publish-container"
            @blur="hBlur"
          ></quill-editor>
        </el-form-item>

        <el-form-item label="封面">
          <el-radio-group v-model="form.coverType" @change="hCoverTypeChange">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label=3>三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.coverType > 0">
          <el-row>
            <el-col :span="6" v-for="(item,idx) in form.coverType" :key="idx">
              <!-- 封面组件 -->
              <my-cover v-model="coverImages[idx]" />
            </el-col>
          </el-row>

        </el-form-item>
        <!-- 频道组件 -->
        <my-channel v-model="form.channelId"></my-channel>

        <el-form-item>
          <el-button :loading="isLoading" type="primary" @click="hUpdate(false)"
            >发表</el-button
          >

          <el-button :loading="isLoading" @click="hUpdate(true)"
            >存入草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    // 注册
    quillEditor
  },
  data () {
    return {
      // 富文本编辑器配置对象
      editorOption: {
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在5到30之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          { min: 20, max: 30000, message: '最少20个字', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择频道', trigger: 'blur' }
        ]
      },
      form: {
        title: '',
        content: '离开你六十年，但愿能认得出你的子女',
        coverType: '',
        channelId: ''

      },
      coverImages: [], // 用来存放封面地址的数组
      isLoading: false
    }
  },
  methods: {
    async getArticleContent (id) {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/articles/' + id,
          method: 'GET'
        })
        console.log(res);
        this.$message.success('获取文章详情成功')
        this.form.title = res.data.data.title
        this.form.content = res.data.data.content
        this.form.channelId = res.data.data.channel_id
        this.form.coverType = res.data.data.cover.type
        this.coverImages = res.data.data.cover.images
      } catch (err) {
        console.log(err);
        this.$message.error('获取文章详情失败')
      }
    },
    // 构造请求参数
    buildData () {
      const data = {
        title: this.form.title,
        content: this.form.content,
        channel_id: this.form.channelId,
        cover: {
          type: this.form.coverType, // 封面类型（张数）
          images: this.coverImages
        }
      };
      return data;
    },
    async doUpdate (draft, id) {
      this.isLoading = true;
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/articles/' + id,
          method: 'PUT',
          params: {
            draft
          },
          data: this.buildData()

        })
        console.log(res);
        this.isLoading = false;
        this.$message.success('修改文章成功')
        this.$router.push('/articles')
      } catch (err) {
        console.log(err);
        this.isLoading = false;
        this.$message.error('修改文章失败')
      }
    },
    // 更新文章内容
    hUpdate (draft) {
    // 手动验证规则
      this.$refs.form.validate(valid => {
        if (valid) {
          const id = this.$route.params.id
          this.doUpdate(draft, id)
        }
      })
    },
    // 富文本框失去了焦点
    hBlur () {
      console.log('富文本框失去了焦点')
      // 手动去触发对应的el-form-item项去验证
      //  this.$refs.formItem : 找到要验证的那个form-item
      //  validate是form-item对象上的方法，
      //  validate('blur'): 验证失焦的情况
      this.$refs.formItem.validate('blur')
    },
    // 切换封面类型执行的回调
    hCoverTypeChange () {
      if (this.form.coverType === 1) {
        // 若封面是单张图片，让数组的长度等于1，只会保留数组的第一个元素，其余元素的清除
        this.coverImages.length = 1
      }
    }
  },
  created () {
    this.getArticleContent(this.$route.params.id)
  }

}
</script>

<style scoped lang='less'>
// 在父组件中去设置子组件的样式，加上/deep/ 实现穿透功能
.publish-container /deep/ .ql-editor {
  height: 300px;
}
.publish-container /deep/ .ql-toolbar.ql-snow {
  padding: 0 8px;
}
</style>
